import { _decorator, Component, Node, Rect, UITransform, v2, Vec3, } from 'cc'
import { BagGrilditem } from './Grild/BagGrilditem'
import { WeapItem } from './Weap/WeapItem'
import { weapMgr } from './Mgr/WeapManager'
import { eventMgr } from '../../Runtime/EventManager'
import { GameEvent } from '../../Runtime/GameEvent'
import { GridMgr } from './Mgr/GrildManager'

const { ccclass, property } = _decorator

@ccclass('popupBagUI')
export class popupBagUI extends Component {
  /**武器相关 */
  @property(Node)
  initWeapList: Node = null
  @property(Node)
  occupyWeapList: Node = null
  @property(Node)
  moveWeapList: Node = null

  @property(Node)
  allGrildList: Node = null
  @property(Node)
  editorShap: Node = null

  /**当前场景点击的武器 */
  private curtouchWeapItem: WeapItem = null
  start() {
    weapMgr.init().then(() => {
      eventMgr.emit(GameEvent.PLACE_WEAP_UPDATE, this.initWeapList)
    })
    GridMgr.init().then(() => {
      eventMgr.emit(GameEvent.PLACE_GRID_START, this.allGrildList);
      this.adoptAllBag();

    })
  }
  /**武器和格子位置适配 */
  protected adoptAllBag() {
    const size = this.allGrildList.getComponent(UITransform).contentSize;
    this.moveWeapList.getComponent(UITransform).setContentSize(size);

    this.occupyWeapList.getComponent(UITransform).setContentSize(size);

    //偏移量
    const offset = (GridMgr.GrildMaxSize.col - 3) * GridMgr.GridData.space;

    this.allGrildList.setPosition(-size.width / 2 + offset, -size.height / 2);
    this.moveWeapList.setPosition(-size.width / 2 + offset, -size.height / 2);
    this.occupyWeapList.setPosition(-size.width / 2 + offset, -size.height / 2);
  }
  protected onEnable(): void {

    eventMgr.on(GameEvent.WEAPON_CLICK, this.clickWeapStart, this);
    eventMgr.on(GameEvent.ADD_WEAP_MOVE, this.addWeapMove, this);
    eventMgr.on(GameEvent.PLACE_WEAP_MOVING, this.checkWeapMove, this);
    eventMgr.on(GameEvent.PLACE_WEAP_END, this.placeWeap, this);
  }

  protected onDisable(): void {
    eventMgr.off(GameEvent.WEAPON_CLICK, this.clickWeapStart)
    eventMgr.off(GameEvent.ADD_WEAP_MOVE, this.addWeapMove)
    eventMgr.off(GameEvent.PLACE_WEAP_MOVING, this.checkWeapMove)
    eventMgr.off(GameEvent.PLACE_WEAP_END, this.placeWeap)
  }

  addWeapMove() {
    this.curtouchWeapItem.node.parent = this.moveWeapList
  }
  initStatus(cItem: WeapItem) {
    const gridChildren = this.allGrildList.children
    const weapKey = cItem.m_weapItemData.weapKey;
    cItem.setDeafult();

    for (let m = 0; m < cItem.indexOnGrid.length; m++) {
      const element = gridChildren[cItem.indexOnGrid[m]].getComponent(BagGrilditem);
      const gridObj = element.gridObj;
      GridMgr.gridMapArr[gridObj.col][gridObj.row] = '0';
    }
    cItem.indexOnGrid = [];
    GridMgr.removeWeapItemByWeapKey(weapKey)
  }
  clickWeapStart(weapNode: Node) {
    this.curtouchWeapItem = weapNode.getComponent(WeapItem);
  }
  // 武器移动
  checkWeapMove() {

    this.initStatus(this.curtouchWeapItem);
    const weap_blockArr = this.curtouchWeapItem.getWeapGridMap();
    let pointPosArr: Vec3[] = [];//武器所有点的坐标

    for (let n = 0; n < weap_blockArr.length; n++) {
      const weapBlock = weap_blockArr[n];
      let tieldPos = GridMgr.getGridPosByColRow(weapBlock.x, weapBlock.y);
      let wpos = this.curtouchWeapItem.point.getComponent(UITransform).convertToWorldSpaceAR(tieldPos);
      let pos = this.curtouchWeapItem.node.parent.getComponent(UITransform).convertToNodeSpaceAR(wpos);

      pointPosArr.push(pos);
    }
    this.checkGridStatusByWeap(pointPosArr);
  }
  checkGridStatusByWeap(posArr: Vec3[]) {
    let gridIndexArr: number[] = [];
    const gridChildren = this.allGrildList.children

    for (let n = 0; n < posArr.length; n++) {
      const checkPos = posArr[n];
      let index = -1;
      for (let m = 0; m < gridChildren.length; m++) {
        const element = gridChildren[m];
        let srcGrid = element.getComponent(BagGrilditem)
        let pos = GridMgr.getGridPosByColRow(srcGrid.gridObj.col, srcGrid.gridObj.row);
        let width = GridMgr.GridData.width;
        let height = GridMgr.GridData.height;

        let rect = new Rect(pos.x - width / 2, pos.y - height / 2, width, height);
        if (rect.contains(v2(checkPos.x, checkPos.y))) {
          index = m;
          break;
        }

      }
      gridIndexArr.push(index);
    }
    GridMgr.curWeapOnGridArr = gridIndexArr;

    this.checMovekWeapPlace(gridIndexArr);

  }
  /**根据区域判断是否放置 */
  checMovekWeapPlace(gridIndexArr: number[]) {

    let placeWeaponKeyArr: string[] = [];//被占用可抖动的武器
    const gridChildren = this.allGrildList.children;
    let itemKey = this.curtouchWeapItem.m_weapItemData.key;
    if (gridIndexArr.indexOf(-1) !== -1) {//超出区域(占用和未占用)
      for (let j = 0; j < gridChildren.length; j++) {
        let srcGrid = gridChildren[j].getComponent(BagGrilditem)
        if (gridIndexArr.indexOf(j) !== -1) {
          const gridObj = srcGrid.gridObj;
          const weapKey = GridMgr.gridMapArr[gridObj.col][gridObj.row];
          // 被占用
          if (weapKey) {
            srcGrid.setRed();
            //被占用的武器抖动状态
            if (placeWeaponKeyArr.indexOf(weapKey) == -1) {
              placeWeaponKeyArr.push(weapKey);
            }
          }
          else {
            srcGrid.setYellow();
          }
        }
        else {
          srcGrid.setDeafult();
        }
      }
    }
    else {//在区域内
      //放置成功设置weapkey到gridMapArr；
      let weapKey = '';
      //可以合成key(wid)和type都相同且相同数量和weapsize相同
      let sameWeapcount = 0;

      for (let i = 0; i < gridChildren.length; i++) {
        let srcGrid = gridChildren[i].getComponent(BagGrilditem)
        if (gridIndexArr.indexOf(i) !== -1) {
          srcGrid.setGreen();
          //抖动和合成状态
          const gridObj = srcGrid.gridObj;
          weapKey = GridMgr.gridMapArr[gridObj.col][gridObj.row];
          //检测武器id是否相同
          if (GridMgr.checkSameWeapoIdByKey(weapKey, itemKey)) {
            sameWeapcount++;
          }
          //添加到抖动列表
          if (placeWeaponKeyArr.indexOf(weapKey) == -1) {
            placeWeaponKeyArr.push(weapKey);
          }
        }
        else {
          srcGrid.setDeafult();
        }
      }
      //TODO:合成判断 ing....
      if (sameWeapcount == gridIndexArr.length) {
        let level = this.curtouchWeapItem.m_weapItemData.level;

        let type = this.curtouchWeapItem.m_weapItemData.type;
        if (weapMgr.checkWeaponByLevelType(level + 1, type)) {
          this.curtouchWeapItem.setYellow();

          eventMgr.emit(GameEvent.WEAPON_UPGRADE);
        }
      }

    }
    //处理逻辑抖动
    eventMgr.emit(GameEvent.WEAP_STOP_ANi);
    for (let ii = 0; ii < placeWeaponKeyArr.length; ii++) {
      const weapkeys = placeWeaponKeyArr[ii];
      eventMgr.emit(GameEvent.WEAPON_SHAKE, weapkeys);
    }

  }
  placeWeap() {
    //1.放置 2.替换 3.卸下
    let gridIndexArr = GridMgr.curWeapOnGridArr
    if (gridIndexArr.indexOf(-1) !== -1) {
      //卸下
      this.curtouchWeapItem.node.parent = this.initWeapList;
    } else {
      /* 1.放置 */
      this.checkExchange();
      this.setGridMapArr();

      const setPos = GridMgr.getItemPosByTiledObj(gridIndexArr)
      this.curtouchWeapItem.node.setPosition(setPos);

      GridMgr.setWeapItemByWeapKey(this.curtouchWeapItem)
      this.curtouchWeapItem.node.parent = this.occupyWeapList;
    }
    eventMgr.emit(GameEvent.WEAP_STOP_ANi)

    GridMgr.initGridStatus();

  }
  /**2.替换(替换，升级) */
  checkExchange() {
    const gridChildren = this.allGrildList.children;
    let gridIndexArr = GridMgr.curWeapOnGridArr
    for (let i = 0; i < gridIndexArr.length; i++) {
      let index = gridIndexArr[i];
      const srcGrid = gridChildren[index].getComponent(BagGrilditem);
      const gridObj = srcGrid.gridObj;
      let weapKey = GridMgr.gridMapArr[gridObj.col][gridObj.row];
      if (weapKey != '0') {

        const cItem = GridMgr.getWeapItemByWeapKey(weapKey);
        if (!cItem) continue;

        this.initStatus(cItem);
        cItem.node.parent = this.initWeapList;
      }
    }
  }

  setGridMapArr() {
    let gridIndexArr = GridMgr.curWeapOnGridArr
    const gridChildren = this.allGrildList.children;
    for (let ii = 0; ii < gridIndexArr.length; ii++) {
      let index = gridIndexArr[ii];
      const srcGrid = gridChildren[index].getComponent(BagGrilditem);
      const gridObj = srcGrid.gridObj;
      this.curtouchWeapItem.indexOnGrid.push(index);
      GridMgr.gridMapArr[gridObj.col][gridObj.row] = this.curtouchWeapItem.m_weapItemData.weapKey;
    }
  }
  //刷新按钮
  onClickUpdateSelectItem() {
    this.initWeapList.removeAllChildren()
    eventMgr.emit(GameEvent.PLACE_WEAP_UPDATE, this.initWeapList)
  }

  MoveGrild() {
    // this.
  }


  update(deltaTime: number) { }
  onClickEditorshape() {
    this.editorShap.active = !this.editorShap.active
  }
}
